#!/home/joshua/.pyenv/versions/anaconda3/bin/python
"""
要求：

    1. 程序名称 contact
    2. 程序功能：
        1. 添加联系人到数据库中
        2. 查询数据库中的联系人
        3. 删除联系人
        4. 修改联系人的属性
    3. 联系人的信息有这些：名字，性别，电话
    4. 使用面向对象的编码方式
    5. 程序的运行方式
        在命令行输入 contact，然后回车可以执行
"""

import sys
from os.path import basename


def open_db():
    try:
        db = open(dbpath, 'r+')
    except FileNotFoundError:
        db = open(dbpath, 'w+')
    return db


def add():
    # 程序以交互式的形式询问联系人的数据：名字，性别，电话
    name = input('Name: ')
    gender = input('Gender: ')
    phone = input('Phone: ')

    db = open_db()

    # 检查数据库中是否已经有同名的记录
    for line in db:
        name_in_db = line.split(sep)[0]
        if name_in_db == name:  # 联系人已经存在
            print('contact %s exists' % name)
            return

    # 数据库中不存在同名记录，此时可以添加新记录
    # 1. 一行一条记录
    # 2. 一行中，用冒号做分隔符
    db.seek(0, 2)   # 把文件指针移动到文件尾部
    record = '%s:%s:%s\n' % (name, gender, phone)
    db.write(record)


def delete():
    try:
        name = sys.argv[2]
    except IndexError:
        print('Require a name')
        return

    db = open_db()
    lines = db.read().splitlines(keepends=True)
    db.seek(0)
    db.truncate(0)
    for line in lines:
        if not line.startswith(name + ':'):
            db.write(line)


def modify():
    try:
        name = sys.argv[2]
    except IndexError:
        print('Require a name')
        return

    db = open_db()
    lines = db.read().splitlines(keepends=True)
    for idx, line in enumerate(lines):
        if line.startswith(name + ':'):
            name, gender, phone = line.strip().split(':')
            del lines[idx]
            break
    else:
        print('no record found')
        return

    # 从用户获取新的值
    orig_name = name
    name = input('Name: [%s] ' % name) or name
    gender = input('Gender: [%s] ' % gender) or gender
    phone = input('Phone: [%s] ' % phone) or phone

    # 检查，新的名字是否与其他名字相同
    if name != orig_name:    # 名字发生改变了
        for line in lines:
            name_in_db = line.split(sep)[0]
            if name_in_db == name:  # 联系人已经存在
                print('name %s already exists' % name)
                return

    # 写入记录的新值，以及其它记录的值
    lines.append('%s:%s:%s\n' % (name, gender, phone))
    db.seek(0)
    db.truncate(0)
    for line in lines:
        db.write(line)


def list_():
    db = open_db()
    lines = db.read().splitlines(keepends=True)
    for line in lines:
        name, gender, phone = line.strip().split(':')
        print('Name: %s, Gender: %s, Phone: %s' % (name, gender, phone))


def search():
    try:
        keyword = sys.argv[2]
    except IndexError:
        print('Require a keyword')
        return

    db = open_db()
    lines = db.read().splitlines(keepends=True)
    for line in lines:
        name, gender, phone = line.strip().split(':')
        if keyword in name:
            print('Name: %s, Gender: %s, Phone: %s' % (name, gender, phone))
            return
    else:
        print('no record found')


dbpath = 'contact.db'
sep = ':'


if __name__ == '__main__':

    # 处理命令行参数
    if len(sys.argv) < 2:
        print('usage: %s cmd <arguments>' % basename(sys.argv[0]))

    subcmd = sys.argv[1]

    if subcmd == 'add':
        add()
    elif subcmd == 'del':
        delete()
    elif subcmd == 'mod':
        modify()
    elif subcmd == 'list':
        list_()
    elif subcmd == 'search':
        search()
    else:
        print('command %s is not supported' % subcmd)
